package com.cy;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 基于此类处理限流/熔断时间触发时出现的异常
 * 说明:
 * 1)系统有默认处理限流,熔断时间触发的异常的处理吗?(DefaultBlockExceptionHandler)
 * 2)当默认处理异常的方式不满足业务需求时,我们需要自己定义异常处理器
 * 3)我们自己定义异常处理器时需要实现BlockExceptionHandler接口,
 * 并将异常处理器对象交给spring管理
 * 4)我们自定义了异常处理器以后,默认的就无效了.*/
@Component
public class ServiceBlockExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest,
                       HttpServletResponse httpServletResponse, BlockException e)
            throws Exception {
        Map<String,Object> map = new HashMap<>();
        map.put("status", 429);
        map.put("message", "访问频繁");
        //将map对象转换为json格式字符串
        //借助jackson中的api  (ObjectMapper)中的writeValueAsString 方法进行转换
        String jsonStr = new ObjectMapper().writeValueAsString(map);
        //设置相应数据编码
        httpServletResponse.setCharacterEncoding("utf8");
        //告诉客户端(浏览器)向他输出的数据类型及内容编码
        httpServletResponse.setContentType("text/html;charset=utf8");
        PrintWriter out = httpServletResponse.getWriter();
        out.println(jsonStr);
        out.flush();


    }
}
